package com.sanri.tools.modules.sqlite;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import com.sanri.tools.modules.core.service.file.FileManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;

@Component
@Slf4j
public class SqliteHelper implements InitializingBean {
    @Autowired
    private FileManager fileManager;

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    public String dbfilePath(){
        File dir = fileManager.mkDataDir("sqlite");
        File file = new File(dir, "data.db");
        try {
            file.createNewFile();
        } catch (IOException e) {
            log.error("数据文件创建失败: {}", file.getAbsolutePath());
        }
        return file.getAbsolutePath();
    }

    /**
     * 创建一个数据源
     * @param connName
     * @return
     * @throws IOException
     * @throws SQLException
     */
    private DruidDataSource createDataSource() throws IOException, SQLException {
        final DruidDataSource druidDataSource = new DruidDataSource();
        String dbfilePath = dbfilePath();
        druidDataSource.setUrl("jdbc:sqlite:"+dbfilePath);
        druidDataSource.setDriverClassName("org.sqlite.JDBC");

        // 连接失败时, 只尝试 5 次
        druidDataSource.setConnectionErrorRetryAttempts(5);
        druidDataSource.setBreakAfterAcquireFailure(true);
        return druidDataSource;
    }

    public DruidPooledConnection getConnection() throws IOException, SQLException {
        DruidDataSource dataSource = createDataSource();
        DruidPooledConnection connection = dataSource.getConnection();
        return connection;
    }

}
